package com.sanery.dao;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	private static SqlSessionFactory fty = null;
	// ThreadLocal线程变量,相当于request作用域，线程内共享数据
	private static ThreadLocal<SqlSession> threadMap = new ThreadLocal<SqlSession>();
	static {
		try {
			String resource = "mybatis-cfg.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			fty = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

	public static SqlSession getSession() {
		SqlSession session = threadMap.get();// 先去看看线程作用域中有没有session
		if (session == null) {// 没有的话，就创建一个，并且放在线程作用域给自己公用
			session = fty.openSession();
			threadMap.set(session);
		}
		return session;
	}

	public static void closeSession() {
		SqlSession session = threadMap.get();
		if (session != null) {
			session.close();
			threadMap.remove();// 关闭的时候，对threadLocal做一些清理动作
		}
	}
}